import Taro from '@tarojs/taro'
import apiUrl from './urls.js'
import { post } from './request/request'
import feedsKeys from './feedsKeys.js'
import { handleStore, getStoreData } from "./init";
const sessionIdMap = {}

function setFeedsSessionId(cardId, sessionId) {
  if (!cardId) return
  sessionIdMap[cardId] = sessionId
}

function getFeedsSessionId(cardId) {
  return sessionIdMap[cardId]
}

function feedsReport(key, params, options = {}) {
  const u = getStoreData('userInfo');
  const c= getStoreData('card');
  

  if (typeof key === 'string') {
    key = feedsKeys[key]
  }

  if (!key) {
    throw new Error('缺少feeds流类型')
  }
  const cardId = c.__cardId
  const userInfo = u.__userInfo
  const bindStaffCardId = u.__bindStaffCardId
  const isBindStaff = u.__isBindStaff
 
  if (!cardId || !userInfo) return

  if (isBindStaff && bindStaffCardId === cardId) return

  const feedsSessionId = getFeedsSessionId(cardId)

  const formData = {
    templateId: key,
    to: cardId,
    feedsSessionId,
    from: userInfo.userId,
    userName: userInfo.nickName,
    ...options,
    params: params || {}
  }

  if (key === 2050) {
    post(apiUrl.feedsStatReportUrl, formData, { silentFail: true }).then(
      () => {},
      () => {}
    )
    return
  }

  post(apiUrl.feedsReportUrl, formData, { silentFail: true }).then(
    () => {},
    () => {}
  )
}

export { setFeedsSessionId, getFeedsSessionId ,feedsReport }
